package com.hup.joystick.service.joyEvent;

import com.hup.joystick.constant.DeviceKey.KeyType;
import com.hup.joystick.constant.DeviceKey.StandardKeys;
import com.hup.joystick.model.FunctionConfig;
import com.hup.joystick.model.joystick.StandardEvent;
import com.hup.joystick.model.joystick.StandardEvent.StandardAction;
import com.hup.joystick.model.joystick.StandardKey;
import com.hup.joystick.view.volumeMenu.VolumeMenu;
import com.hup.utils.commons.start.SpringContext;
import lombok.extern.log4j.Log4j2;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

/**
 * @author hugan
 * @date 2020/11/18
 */
@Log4j2
public class VolumeMenuFunctionHandler implements IJoyEventHandler, ActionListener {
    private static final int LONG_PRESS_SPAN = 200;

    private final Timer timerLongPress = new Timer(LONG_PRESS_SPAN, this);
    private final VolumeMenu volumeMenu;
    private String lastPressArrow;

    public VolumeMenuFunctionHandler() {
        volumeMenu = SpringContext.getBean(VolumeMenu.class);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //log.info("");
        if (!volumeMenu.isVisible()) {
            timerLongPress.stop();
            return;
        }
        volumeMenu.onPressJoyArrow(lastPressArrow, true);
    }

    @Override
    public void releaseAllActiveFunction() {
        if (!volumeMenu.isVisible()) return;
        timerLongPress.stop();
        //快捷菜单打开后,隐藏
        volumeMenu.dispose();
    }

    @Override
    public void handleRelease(StandardEvent e, StandardKey standardKey) {
        if (!volumeMenu.isVisible()) return;
        timerLongPress.stop();
    }

    @Override
    public void handlePress(ArrayList<StandardAction> newPress, ArrayList<StandardAction> currentPress,
            FunctionConfig matchConfig) {
    }

    @Override
    public boolean handlePressAndConsume(StandardEvent e, ArrayList<StandardAction> newPress,
            FunctionConfig matchConfig) {
        //log.info("isVisible={}", volumeMenu.isVisible());
        if (!volumeMenu.isVisible()) return false;

        //方向键
        for (StandardAction press : newPress) {
            if (press.standardKey.type == KeyType.ARROW) {
                log.debug("key={}", press.standardKey.key);
                lastPressArrow = press.standardKey.key;
                volumeMenu.onPressJoyArrow(lastPressArrow, false);
                timerLongPress.restart();
                return true;
            } else if (StandardKeys.A.key.equals(press.standardKey.key)) {
                timerLongPress.stop();
                volumeMenu.dispose();
                return true;
            }
        }
        return true;
    }

}
